<!-- camera_solve.html -->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>摄像机处理</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 1000px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background-color: white;
            border-radius: 10px;
            padding: 30px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            text-align: center;
        }
        h1 {
            color: #333;
            margin-bottom: 30px;
        }
        .video-container {
            margin: 20px auto;
            width: 100%;
            max-width: 640px;
        }
        #videoElement {
            width: 100%;
            max-width: 640px;
            height: auto;
            border: 2px solid #ddd;
            border-radius: 8px;
            background-color: #000;
        }
        .controls {
            margin: 20px 0;
        }
        button {
            background-color: #007bff;
            color: white;
            padding: 12px 24px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
            margin: 0 10px;
        }
        button:hover {
            background-color: #0056b3;
        }
        button:disabled {
            background-color: #cccccc;
            cursor: not-allowed;
        }
        .status {
            margin: 15px 0;
            padding: 10px;
            border-radius: 5px;
            font-weight: bold;
        }
        .error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .info {
            background-color: #d1ecf1;
            color: #0c5460;
            border: 1px solid #bee5eb;
        }
        .snapshot-container {
            margin: 20px auto;
            text-align: center;
        }
        #snapshotCanvas {
            max-width: 100%;
            border: 2px solid #ddd;
            border-radius: 8px;
            display: none;
        }
        .back-link {
            display: inline-block;
            margin-top: 20px;
            padding: 10px 20px;
            background-color: #6c757d;
            color: white;
            text-decoration: none;
            border-radius: 5px;
        }
        .back-link:hover {
            background-color: #5a6268;
        }
        .camera-selector {
            margin: 15px 0;
        }
        select {
            padding: 10px;
            font-size: 16px;
            border-radius: 5px;
            border: 1px solid #ddd;
            margin: 0 10px;
        }
        .facing-mode-selector {
            margin: 15px 0;
        }
        
        /* 添加加载动画样式 */
        .loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid #f3f3f3;
            border-top: 3px solid #007bff;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-right: 10px;
            vertical-align: middle;
        }
 
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
</head>
<body>
    <div style="margin-bottom: 20px;">
        <a href="index.html" style="display: inline-block; padding: 10px 15px; background-color: #6c757d; color: white; text-decoration: none; border-radius: 5px;">← 返回主页</a>
    </div>
    <div class="container">
        <h1>摄像机处理</h1>
        
        <div class="video-container">
            <video id="videoElement" autoplay playsinline muted></video>
        </div>
        
        <div class="facing-mode-selector">
            <label>
                <input type="radio" name="facingMode" value="user" checked> 前置摄像头
            </label>
            <label style="margin-left: 20px;">
                <input type="radio" name="facingMode" value="environment"> 后置摄像头
            </label>
        </div>
        
        <div class="camera-selector">
            <label for="cameraSelect">选择具体摄像头:</label>
            <select id="cameraSelect" disabled>
                <option value="">自动选择</option>
            </select>
        </div>
        
        <div class="controls">
            <button id="startCameraBtn">启动摄像机</button>
            <button id="stopCameraBtn" disabled>停止摄像机</button>
            <button id="snapshotBtn" disabled>拍照</button>
            <button id="detectBtn" disabled>发送检测</button>
            <button id="realTimeBtn" disabled>开始实时识别</button>
        </div>
        
        <div id="statusMessage" class="status info">
            点击"启动摄像机"按钮开始使用摄像头
        </div>
        
        <div class="snapshot-container">
            <canvas id="snapshotCanvas"></canvas>
        </div>
        
        <a href="../index.html" class="back-link">返回主页</a>
    </div>
 
    <script>
        // 获取页面元素
        const videoElement = document.getElementById('videoElement');
        const startCameraBtn = document.getElementById('startCameraBtn');
        const stopCameraBtn = document.getElementById('stopCameraBtn');
        const snapshotBtn = document.getElementById('snapshotBtn');
        const statusMessage = document.getElementById('statusMessage');
        const snapshotCanvas = document.getElementById('snapshotCanvas');
        const canvasContext = snapshotCanvas.getContext('2d');
        const cameraSelect = document.getElementById('cameraSelect');
        const facingModeRadios = document.getElementsByName('facingMode');
        const detectBtn = document.getElementById('detectBtn');
        const realTimeBtn = document.getElementById('realTimeBtn');
        
        // 存储媒体流对象和设备列表
        let mediaStream = null;
        let availableCameras = [];
        let isRealTimeDetection = false;
        let realTimeDetectionInterval = null;
        const detectionInterval = 1500; 
        let backendUrl = null;
        
        // 更新状态消息
        function updateStatus(message, type = 'info') {
            // 如果是处理中的状态，添加加载动画
            if (type === 'info' && message.includes('正在处理')) {
                statusMessage.innerHTML = '<div class="loading"></div>' + message;
            } else {
                statusMessage.textContent = message;
            }
            statusMessage.className = `status ${type}`;
        }
 
        async function initializeApp() {
            try {
                // 设置本地后端URL
                backendUrl = 'http://localhost:5000/predict';
                const healthUrl = 'http://localhost:5000/health';
                
                // 测试健康检查端点
                try {
                    console.log('正在测试健康检查端点:', healthUrl);
                    
                    // 直接调用本地健康检查端点
                    const healthResponse = await fetch(healthUrl);
                    
                    if (healthResponse.ok) {
                        const healthData = await healthResponse.json();
                        console.log('健康检查成功:', healthData);
                        updateStatus('健康检查通过，后端服务正常运行', 'success');
                    } else {
                        console.warn('健康检查失败:', healthResponse.status);
                        updateStatus('后端服务可能不可用: ' + healthResponse.status, 'info');
                    }
                } catch (healthError) {
                    console.error('健康检查失败:', healthError);
                    updateStatus('无法连接到后端服务: ' + healthError.message, 'error');
                }
                
                return backendUrl;
            } catch (error) {
                console.error('获取配置失败:', error);
                updateStatus('获取后端配置失败: ' + error.message, 'error');
                return null;
            }
        }
 
        // 压缩图像函数
        function compressImage(canvas, maxWidth, quality) {
            const width = canvas.width;
            const height = canvas.height;
            
            if (width <= maxWidth) {
                // 如果图像宽度已经小于等于最大宽度，直接压缩质量
                return canvas.toDataURL('image/jpeg', quality);
            }
            
            // 创建临时画布用于缩放图像
            const tempCanvas = document.createElement('canvas');
            const tempCtx = tempCanvas.getContext('2d');
            
            // 计算新的尺寸
            const scale = maxWidth / width;
            tempCanvas.width = maxWidth;
            tempCanvas.height = height * scale;
            
            // 绘制缩放后的图像
            tempCtx.drawImage(canvas, 0, 0, tempCanvas.width, tempCanvas.height);
            
            // 返回压缩后的图像数据
            return tempCanvas.toDataURL('image/jpeg', quality);
        }
 
        async function sendToBackendForDetection() {
            if (!mediaStream) {
                updateStatus('请先启动摄像头', 'error');
                return;
            }
            
            try {
                // 拍照
                takeSnapshot();
                
                const imageData = compressImage(snapshotCanvas, 640, 0.8);
                
                // 发送到后端进行检测
                updateStatus('正在处理图像...', 'info');
                
                // 直接调用本地YOLO服务
                const response = await fetch(backendUrl, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ image: imageData })
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                const result = await response.json();
                
                if (result.status === 'success') {
                    // 显示处理后的图像
                    const processedImage = new Image();
                    processedImage.onload = function() {
                        // 固定画布尺寸以避免忽大忽小
                        const displayWidth = 640;
                        const scale = displayWidth / processedImage.width;
                        const displayHeight = processedImage.height * scale;
                        
                        snapshotCanvas.width = displayWidth;
                        snapshotCanvas.height = displayHeight;
                        
                        // 在画布上显示处理后的图像
                        canvasContext.clearRect(0, 0, snapshotCanvas.width, snapshotCanvas.height);
                        canvasContext.drawImage(processedImage, 0, 0, snapshotCanvas.width, snapshotCanvas.height);
                        
                        // 显示画布
                        snapshotCanvas.style.display = 'block';
                        
                        updateStatus(`检测完成，发现 ${result.detections.length} 个目标`, 'success');
                        
                        // 显示检测信息
                        if (result.detections.length > 0) {
                            console.log('检测结果:', result.detections);
                        }
                    };
                    processedImage.src = 'data:image/jpeg;base64,' + result.processed_image;
                } else {
                    updateStatus('检测失败: ' + result.error, 'error');
                }
            } catch (error) {
                console.error('处理图像时出错:', error);
                updateStatus('处理图像时出错: ' + error.message, 'error');
            }
        }
 
        async function getAvailableCameras() {
            try {
                // 获取媒体设备列表
                const devices = await navigator.mediaDevices.enumerateDevices();
                // 过滤出视频输入设备
                availableCameras = devices.filter(device => device.kind === 'videoinput');
                
                // 清空选择器
                cameraSelect.innerHTML = '<option value="">自动选择</option>';
                
                // 添加摄像头选项
                availableCameras.forEach((camera, index) => {
                    const option = document.createElement('option');
                    option.value = camera.deviceId;
                    // 如果有标签名则使用标签名，否则使用默认名称
                    option.text = camera.label || `摄像头 ${index + 1}`;
                    cameraSelect.appendChild(option);
                });
                
                // 启用选择器
                cameraSelect.disabled = false;
                
                return availableCameras;
            } catch (error) {
                console.error('获取摄像头列表失败:', error);
                updateStatus('获取摄像头列表失败: ' + error.message, 'error');
                return [];
            }
        }
        
        // 启动指定摄像头 - 使用更简单的实现方式
        async function startCamera(options = {}) {
            try {
                // 更新状态
                updateStatus('正在请求访问摄像头...', 'info');
                
                // 如果当前正在使用摄像头，先停止
                if (mediaStream) {
                    const tracks = mediaStream.getTracks();
                    tracks.forEach(track => track.stop());
                }
                
                // 构建约束条件 - 使用更简单的实现
                let constraints = { video: true, audio: false };
                
                // 如果指定了摄像头ID，则使用具体设备
                if (options.deviceId) {
                    constraints = {
                        video: { deviceId: { exact: options.deviceId } },
                        audio: false
                    };
                } 
                // 否则使用 facingMode
                else if (options.facingMode) {
                    constraints = {
                        video: { facingMode: options.facingMode },
                        audio: false
                    };
                }
                
                // 获取用户媒体设备权限
                mediaStream = await navigator.mediaDevices.getUserMedia(constraints);
                
                // 将视频流设置为视频元素的源
                videoElement.srcObject = mediaStream;
                
                // 确保视频开始播放
                videoElement.play().catch(e => console.error("视频播放失败:", e));
                
                // 更新按钮状态
                startCameraBtn.disabled = true;
                stopCameraBtn.disabled = false;
                snapshotBtn.disabled = false;
                cameraSelect.disabled = false;
                detectBtn.disabled = false;
                realTimeBtn.disabled = false;
                
                // 更新状态消息
                updateStatus('摄像头已启动，正在显示视频流', 'success');
            } catch (error) {
                console.error('访问摄像头时出错:', error);
                updateStatus(`无法访问摄像头: ${error.message}`, 'error');
                startCameraBtn.disabled = false;
                stopCameraBtn.disabled = true;
                snapshotBtn.disabled = true;
                detectBtn.disabled = true;
                realTimeBtn.disabled = true;
            }
        }
        
        // 停止摄像机
        function stopCamera() {
            if (mediaStream) {
                // 停止所有媒体轨道
                const tracks = mediaStream.getTracks();
                tracks.forEach(track => track.stop());
                
                // 清除视频元素的源
                videoElement.srcObject = null;
                
                // 更新按钮状态
                startCameraBtn.disabled = false;
                stopCameraBtn.disabled = true;
                snapshotBtn.disabled = true;
                detectBtn.disabled = true;
                realTimeBtn.disabled = true;
                
                // 更新状态消息
                updateStatus('摄像头已停止', 'info');
                
                // 如果正在实时识别，则停止
                if (isRealTimeDetection) {
                    toggleRealTimeDetection();
                }
            }
        }
        
        // 拍照功能
        function takeSnapshot() {
            if (!mediaStream) return;
            
            // 设置画布尺寸与视频相同
            snapshotCanvas.width = videoElement.videoWidth;
            snapshotCanvas.height = videoElement.videoHeight;
            
            // 将当前视频帧绘制到画布上
            canvasContext.drawImage(videoElement, 0, 0, snapshotCanvas.width, snapshotCanvas.height);
            
            // 显示画布
            snapshotCanvas.style.display = 'block';
            
            // 更新状态消息
            updateStatus('拍照成功！', 'success');
        }
        
        // 切换实时识别状态
        function toggleRealTimeDetection() {
            if (!isRealTimeDetection) {
                // 开始实时识别
                isRealTimeDetection = true;
                realTimeBtn.textContent = '停止实时识别';
                updateStatus('开始实时识别...', 'info');
                
                // 设置定时器，定期发送检测请求
                realTimeDetectionInterval = setInterval(sendFrameForDetection, detectionInterval);
            } else {
                // 停止实时识别
                isRealTimeDetection = false;
                realTimeBtn.textContent = '开始实时识别';
                updateStatus('已停止实时识别', 'info');
                
                // 清除定时器
                if (realTimeDetectionInterval) {
                    clearInterval(realTimeDetectionInterval);
                    realTimeDetectionInterval = null;
                }
            }
        }
 
        // 发送当前帧进行检测 - 添加性能计时和图像压缩
        async function sendFrameForDetection() {
            if (!mediaStream) {
                updateStatus('请先启动摄像头', 'error');
                toggleRealTimeDetection(); // 停止实时识别
                return;
            }
            
            // 开始计时
            const startTime = performance.now();
            
            try {
                // 拍照获取当前帧
                takeSnapshot();
                
                // 压缩图像（最大宽度320px，质量0.6）
                const imageData = compressImage(snapshotCanvas, 320, 0.6);
                
                // 发送到后端进行检测
                updateStatus('正在处理图像...', 'info');
                
                // 直接调用本地YOLO服务
                const response = await fetch(backendUrl, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ image: imageData })
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                // 计算请求发送时间
                const requestTime = performance.now() - startTime;
                console.log(`请求发送耗时: ${requestTime.toFixed(2)}ms`);
                
                const result = await response.json();
                
                // 计算总耗时
                const totalTime = performance.now() - startTime;
                console.log(`总处理耗时: ${totalTime.toFixed(2)}ms`);
                
                if (result.status === 'success') {
                    // 显示处理后的图像
                    const processedImage = new Image();
                    processedImage.onload = function() {
                        // 固定画布尺寸以避免忽大忽小
                        const displayWidth = 640;
                        const scale = displayWidth / processedImage.width;
                        const displayHeight = processedImage.height * scale;
                        
                        snapshotCanvas.width = displayWidth;
                        snapshotCanvas.height = displayHeight;
                        
                        // 在画布上显示处理后的图像
                        canvasContext.clearRect(0, 0, snapshotCanvas.width, snapshotCanvas.height);
                        canvasContext.drawImage(processedImage, 0, 0, snapshotCanvas.width, snapshotCanvas.height);
                        
                        // 显示画布
                        snapshotCanvas.style.display = 'block';
                        
                        updateStatus(`实时检测完成，发现 ${result.detections.length} 个目标 | 耗时: ${totalTime.toFixed(0)}ms`, 'success');
                        
                        // 显示检测信息
                        if (result.detections.length > 0) {
                            console.log('检测结果:', result.detections);
                        }
                    };
                    processedImage.src = 'data:image/jpeg;base64,' + result.processed_image;
                } else {
                    updateStatus('检测失败: ' + result.error, 'error');
                }
            } catch (error) {
                const totalTime = performance.now() - startTime;
                console.error('处理图像时出错:', error);
                updateStatus('处理图像时出错: ' + error.message + ` | 耗时: ${totalTime.toFixed(0)}ms`, 'error');
                
                // 出错时停止实时识别
                toggleRealTimeDetection();
            }
        }
        // 页面加载完成后绑定事件
        document.addEventListener('DOMContentLoaded', async function() {
            await initializeApp();
            
            // 检查浏览器是否支持媒体设备API
            if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
                updateStatus('您的浏览器不支持访问媒体设备，请更换浏览器重试', 'error');
                startCameraBtn.disabled = true;
                return;
            }
            
            // 绑定按钮事件
            startCameraBtn.addEventListener('click', () => {
                const selectedCameraId = cameraSelect.value;
                const facingMode = document.querySelector('input[name="facingMode"]:checked').value;
                
                // 如果选择了具体摄像头，则使用该摄像头
                if (selectedCameraId) {
                    startCamera({ deviceId: selectedCameraId });
                } else {
                    // 否则使用 facingMode
                    startCamera({ facingMode: facingMode });
                }
            });
            
            stopCameraBtn.addEventListener('click', stopCamera);
            snapshotBtn.addEventListener('click', takeSnapshot);
            detectBtn.addEventListener('click', sendToBackendForDetection);
            realTimeBtn.addEventListener('click', toggleRealTimeDetection);
            
            // 摄像头选择事件
            cameraSelect.addEventListener('change', async function() {
                if (this.value) {
                    // 启动选中的摄像头
                    await startCamera({ deviceId: this.value });
                }
            });
            
            // facingMode 选择事件
            facingModeRadios.forEach(radio => {
                radio.addEventListener('change', function() {
                    // 如果当前正在使用摄像头，则切换
                    if (mediaStream) {
                        const selectedCameraId = cameraSelect.value;
                        const facingMode = document.querySelector('input[name="facingMode"]:checked').value;
                        
                        if (selectedCameraId) {
                            startCamera({ deviceId: selectedCameraId });
                        } else {
                            startCamera({ facingMode: facingMode });
                        }
                    }
                });
            });
            
            // 获取可用摄像头列表
            getAvailableCameras();
        });
    </script>
</body>
</html>